// pages/post/post.js
const app = getApp()
//const user = JSON.parse(wx.getStorageSync("user"));
const base_url = app.globalData.base_url;
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title:'',
    topicArr:'',
    topic:[],
    index:null,//选中的话题下标
    fixindex:'',
    content:'',
    imgPaths:[],
    img_url:[],
    video_url:[],
    topic_id:'',
    videolist: [],     //上传视频路径
    videosee: []       //视频预览路径
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '帖子'
    })
    if(options.id){
      fixindex:options.id
    }
    wx.showLoading({
      success:()=>{
        this.init()

      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  init:function(){
    wx.request({
      url: base_url + '/Topic/getTopicList',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: res => {
        wx.hideLoading()
        if (res.data.success == '1' && res.data.data.length != 0) {
          if(this.data.fixindex != ''){
            let topic = res.data.data.filter((v)=>{
              return v.topic_id == this.data.fixindex
            })
          }
          let arrName = res.data.data.map((v,i)=>{
            return v.topic_name
          });
          this.setData({
            topicArr:res.data.data,
            topic:arrName
          })
        }
        
      }
    })
  },
  bindPickerChange:function(e){
    this.setData({
      index: e.detail.value
    })
  },
  getTitle:function(e){
    this.setData({
      title:e.detail.value
    })
  },
  getContent:function(e){
    this.setData({
      content:e.detail.value
    })
  },
  commit:function(){
    if(this.data.title != ''){
      let data = {
        'user_token': JSON.parse(wx.getStorageSync("user")).user_token,
        'title': this.data.title,
        'content': this.data.content,
        'img_url': this.data.img_url,
        "video_url": this.data.videolist
      };
      if(this.data.index){
        data.topic_id = this.data.topicArr[this.data.index].topic_id
      }
    
      wx.showLoading({
        mask:true,
        title:"发布中",
        success:()=>{
          wx.request({
            url: base_url + '/Post/add',
            method: 'POST',
            data:data,
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: res => {
        
              if (res.data.success == '1') {
                wx.navigateTo({
                  url: '../index/index'
                })
              }

            }
          })
        }
      })
    }else{
      wx.showToast({
        title: '标题不能为空',
        icon: 'none',
        duration: 2000
      })
    }
  },
  del(e){
    let types = e.currentTarget.dataset.type;
    //let Arr = types == 0 ? this.data.img_url : this.data.videolist
    let index = types == 0 ? e.currentTarget.dataset.ind:0
    if (types == 0) {
      let Arr = this.data.img_url, imgPaths = this.data.imgPaths;
      Arr.splice(index,1)
      imgPaths.splice(index,1)
      this.setData({
        img_url:Arr,
        imgPaths:imgPaths
      })
    }else{
      this.setData({
        videolist:[],
        videosee:[]
      })
    }
    
  },
  addpic(){
    let itemArr = ['图片','视频'];
    if(this.data.videolist.length>0){
      itemArr= [''];
    }
    if(this.data.imgPaths.length>0){
      itemArr=['图片']
    }
    wx.showActionSheet({
      itemList: itemArr,
      success: res => {
        if (res.tapIndex == 0) {
          wx.chooseImage({
            count: 9,
            sourceType: ['album'],
            success: res => {
              wx.showLoading({
                title: '正在上传图片',
                success: () => {
                  let arr = 'imgPaths[' + this.data.imgPaths.length + ']';
                  if (this.data.imgPaths.length > 0) {
                    var i = this.data.imgPaths.length;
                    this.setData({
                      imgPaths: this.data.imgPaths.concat(res.tempFilePaths)
                    })
                  } else {
                    var i = 0;
                    this.setData({
                      imgPaths: res.tempFilePaths
                    });
                  }
                  let callback = () => {
                    wx.uploadFile({
                      url: base_url + '/File/uploadImage',
                      name: 'uploads',
                      filePath: this.data.imgPaths[i],
                      header: {
                        'content-type': 'multipart/form-data'
                      },
                      success: res => {
                        let data = JSON.parse(res.data);
                        if (data.success == '1') {
                          // let img_url = this.data.formData.img_url.map(v => {
                          //   return v.replace(/http:\/\/118.126.92.149/g, '')
                          // }).join(',')
                          let img_url = this.data.img_url;
                          img_url.push(data.data.path)
                          this.setData({
                            img_url: img_url
                          })
                          i++;//上传张数
                          if (i == this.data.imgPaths.length) {//上传结束
                            wx.hideLoading()
                            wx.showToast({
                              title: '上传成功',
                              mask: true,
                              icon: 'success',
                              duration: 2000
                            })
                          } else {
                            callback()
                          }
                        }
                      }
                    })
                  }
                  callback()
                }
              })


            },
            fail: res => {
              wx.showToast({
                title: '取消上传',
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else {
          let videolist = this.data.videolist,
            videosee = this.data.videosee;
          wx.chooseVideo({
            sourceType: ['album'],
            maxDuration: 60,
            count:1,
            camera: 'back',
            success: res => {
              wx.showLoading({
                title: '上传中',
              })
              wx.uploadFile({
                url: base_url + '/File/uploadVideo',
                name: 'uploads',
                filePath: res.tempFilePath,
                header: {
                  'content-type': 'multipart/form-data'
                },
                success: data => {
                  wx.showToast({
                    title: '上传成功',
                    mask: true,
                    icon: 'success',
                    duration: 2000
                  });
                  wx.hideLoading()
                  let datas=JSON.parse(data.data);
                  videolist.push(datas.data.path)
                  videosee.push(datas.data.video_img)
                
                  this.setData({
                    videolist: videolist,
                    videosee: videosee
                  })
                }
              })
            }
          })
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })    
  },

})
